package clickhousex

import (
	"context"
	"log"
	"time"

	"github.com/ClickHouse/clickhouse-go/v2"
	"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
)

func New(ctx context.Context, hosts []string, database, username, password string) driver.Conn {
	conn, err := clickhouse.Open(&clickhouse.Options{
		Addr: hosts,
		Auth: clickhouse.Auth{
			Database: database,
			Username: username,
			Password: password,
		},
		Settings: clickhouse.Settings{
			"max_execution_time": 60,
			"max_memory_usage":   10000000000,
			"async_insert":       1,
		},
		Compression:      &clickhouse.Compression{Method: clickhouse.CompressionLZ4},
		MaxOpenConns:     25,
		MaxIdleConns:     10,
		ConnMaxLifetime:  10 * time.Minute,
		DialTimeout:      30 * time.Second,
		ConnOpenStrategy: clickhouse.ConnOpenRoundRobin,
		Debug:            false, // 启用调试模式
		Debugf: func(format string, v ...interface{}) {
			// 自定义调试输出
			log.Printf("[ClickHouse Debug] "+format, v...)
		},
	})

	if err != nil {
		panic(err)
	}

	if err := conn.Ping(ctx); err != nil {
		_ = conn.Close()
		panic(err)
	}

	return conn
}
